package com.yindian.cos.easy.security.context;

import lombok.extern.log4j.Log4j2;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 过滤器链的上下文对象
 *
 * @author zhangchuanhao
 * @date 2018/12/14
 */
@Log4j2
public class AuthenticationContext extends ConcurrentHashMap<String, Object> {

    protected static Class<? extends AuthenticationContext> contextClass = AuthenticationContext.class;

    private static AuthenticationContext currentContext = null;

    protected static final ThreadLocal<? extends AuthenticationContext> threadLocal = new ThreadLocal<AuthenticationContext>() {
        @Override
        protected AuthenticationContext initialValue() {
            try {
                log.debug("创建{}", AuthenticationContext.class.getSimpleName());
                return contextClass.newInstance();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
    };

    public AuthenticationContext() {
        super();
    }

    /**
     * 获取当前上下文
     *
     * @return
     */
    public static AuthenticationContext getCurrentContext() {
        if (currentContext != null) {
            return currentContext;
        }
        AuthenticationContext context = threadLocal.get();
        return context;
    }

    /**
     * 设置request
     *
     * @param request
     */
    public void setRequest(HttpServletRequest request) {
        put("request", request);
    }

    /**
     * 获取request
     *
     * @param request
     * @return
     */
    public HttpServletRequest getRequest(HttpServletRequest request) {
        return (HttpServletRequest) get("request");
    }

    /**
     * 设置response
     *
     * @param response
     */
    public void setResponse(HttpServletResponse response) {
        put("response", response);
    }

    /**
     * 获取response
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        return (HttpServletResponse) get("response");
    }

    /**
     * 设置当前的鉴权处理器
     */
    public void setAuthentication(String abstractAuthenticationName) {
        put("abstractAuthenticationName", abstractAuthenticationName);
    }

    /**
     * 获取当前鉴权处理器
     *
     * @return
     */
    public String getAuthentication() {
        return (String) get("abstractAuthenticationName");
    }

    /**
     * 设置filterChain
     *
     * @param filterChain
     */
    public void setFilterChain(FilterChain filterChain) {
        put("filterChain", filterChain);
    }

    /**
     * 获取filterChain
     *
     * @return
     */
    public FilterChain getFilterChain() {
        return (FilterChain) get("filterChain");
    }

    /**
     * 清理上下文
     */
    @Override
    public void clear() {
        super.clear();
        threadLocal.remove();
        log.debug("销毁{}", AuthenticationContext.class.getSimpleName());
    }
}
